package com.spdzen.support.shiro;

import java.util.List;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.shiro.subject.Subject;
import org.apache.shiro.util.CollectionUtils;
import org.apache.shiro.web.filter.authz.AuthorizationFilter;

public class AnyRolesAuthorizationFilter extends AuthorizationFilter {

	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
		Subject subject = getSubject(request, response);
		String[] rolesArray = (String[]) mappedValue;

		if (rolesArray == null) {
			// no roles specified, so nothing to check - allow access.
			return true;
		}

		int len = rolesArray.length;
		if (len == 0) {
			// 如果配置了roles[]，表示所有角色都没有权限。
			return false;
		}

		List<String> roles = CollectionUtils.asList(rolesArray);
		boolean[] hasRoles = subject.hasRoles(roles);
		for (int i = 0; i < len; i++) {
			if (hasRoles[i]) {
				return true;
			}
		}

		return false;
	}

}
